"""
数据库种子数据初始化模块
用于创建示例用户偏好和画像数据，以测试个性化服务功能
"""
import uuid
from datetime import datetime
from sqlalchemy.orm import Session
from src.config.database import SessionLocal
from src.models.user_preference import (
    UserPreference,
    UserProfile,
    PreferredLanguage,
    PreferredModel,
    PreferredResponseStyle
)
from src.utils.logging import get_logger

logger = get_logger(__name__)

def init_seed_data():
    """初始化种子数据"""
    try:
        with SessionLocal() as db:
            # 检查是否已有种子数据
            existing_preferences = db.query(UserPreference).count()
            if existing_preferences > 0:
                logger.info("种子数据已存在，跳过初始化")
                return
            
            # 创建示例用户偏好数据
            create_sample_user_preferences(db)
            
            # 创建示例用户画像数据
            create_sample_user_profiles(db)
            
            # 创建示例内容项数据
            from src.config.seed_recommendation_data import seed_recommendation_data
            content_count = seed_recommendation_data(db)
            logger.info(f"已创建 {content_count} 个示例内容项")
            
            logger.info("种子数据初始化成功")
    except Exception as e:
        logger.error(f"种子数据初始化失败: {e}")
        raise

def create_sample_user_preferences(db: Session):
    """创建示例用户偏好数据"""
    sample_preferences = [
        {
            "user_id": uuid.UUID("12345678-1234-5678-1234-567812345678"),
            "preferred_language": PreferredLanguage.CHINESE,
            "preferred_model": PreferredModel.GPT4,
            "preferred_response_style": PreferredResponseStyle.FRIENDLY,
            "enable_notifications": True,
            "enable_email_notifications": True,
            "enable_sms_notifications": False,
            "timezone": "Asia/Shanghai",
            "theme": "light",
            "preferred_knowledge_sources": ["AI知识库", "技术文档"],
            "custom_settings": {"auto_translate": True, "voice_input": False},
        },
        {
            "user_id": uuid.UUID("23456789-2345-6789-2345-678923456789"),
            "preferred_language": PreferredLanguage.ENGLISH,
            "preferred_model": PreferredModel.CLAUDE,
            "preferred_response_style": PreferredResponseStyle.DETAILED,
            "enable_notifications": False,
            "enable_email_notifications": False,
            "enable_sms_notifications": False,
            "timezone": "America/New_York",
            "theme": "dark",
            "preferred_knowledge_sources": ["学术论文", "研究报告"],
            "custom_settings": {"auto_translate": False, "voice_input": True},
        },
        {
            "user_id": uuid.UUID("34567890-3456-7890-3456-789034567890"),
            "preferred_language": PreferredLanguage.JAPANESE,
            "preferred_model": PreferredModel.GEMINI,
            "preferred_response_style": PreferredResponseStyle.FORMAL,
            "enable_notifications": True,
            "enable_email_notifications": True,
            "enable_sms_notifications": True,
            "timezone": "Asia/Tokyo",
            "theme": "light",
            "preferred_knowledge_sources": ["技术博客", "开源项目"],
            "custom_settings": {"auto_translate": True, "voice_input": True},
        }
    ]
    
    for pref_data in sample_preferences:
        preference = UserPreference(**pref_data)
        db.add(preference)
    
    db.commit()
    logger.info(f"已创建 {len(sample_preferences)} 条用户偏好示例数据")

def create_sample_user_profiles(db: Session):
    """创建示例用户画像数据"""
    # 先获取用户偏好，以便建立关联
    user_preferences = db.query(UserPreference).all()
    
    sample_profiles = [
        {
            "user_preference_id": user_preferences[0].id if len(user_preferences) > 0 else None,
            "user_id": user_preferences[0].user_id if len(user_preferences) > 0 else uuid.UUID("12345678-1234-5678-1234-567812345678"),
            "interests": ["人工智能", "机器学习", "数据分析"],
            "knowledge_levels": {"AI基础": 4, "Python": 3, "数据分析": 3},
            "usage_patterns": {"daily_active_time": 60, "preferred_features": ["智能推荐", "快速回复"]},
            "interaction_history": [
                {"type": "chat", "topic": "AI模型比较", "duration": 15},
                {"type": "research", "topic": "最新LLM技术", "duration": 45}
            ],
            "feedback_scores": {"service_quality": 5, "response_time": 4},
            "user_type": "普通用户"
        },
        {
            "user_preference_id": user_preferences[1].id if len(user_preferences) > 1 else None,
            "user_id": user_preferences[1].user_id if len(user_preferences) > 1 else uuid.UUID("23456789-2345-6789-2345-678923456789"),
            "interests": ["云计算", "DevOps", "微服务"],
            "knowledge_levels": {"AWS": 5, "Docker": 4, "Kubernetes": 3},
            "usage_patterns": {"daily_active_time": 120, "preferred_features": ["知识库", "工作流"]},
            "interaction_history": [
                {"type": "ticket", "topic": "部署问题", "duration": 30},
                {"type": "webinar", "topic": "容器化最佳实践", "duration": 90}
            ],
            "feedback_scores": {"service_quality": 4, "response_time": 5},
            "user_type": "企业用户"
        },
        {
            "user_preference_id": user_preferences[2].id if len(user_preferences) > 2 else None,
            "user_id": user_preferences[2].user_id if len(user_preferences) > 2 else uuid.UUID("34567890-3456-7890-3456-789034567890"),
            "interests": ["网络安全", "渗透测试", "数据加密"],
            "knowledge_levels": {"安全审计": 4, "漏洞评估": 5, "加密技术": 3},
            "usage_patterns": {"daily_active_time": 45, "preferred_features": ["安全建议", "合规检查"]},
            "interaction_history": [
                {"type": "consultation", "topic": "安全漏洞修复", "duration": 60},
                {"type": "training", "topic": "最新安全威胁", "duration": 120}
            ],
            "feedback_scores": {"service_quality": 5, "response_time": 5},
            "user_type": "高级用户"
        }
    ]
    
    for profile_data in sample_profiles:
        profile = UserProfile(**profile_data)
        db.add(profile)
    
    db.commit()
    logger.info(f"已创建 {len(sample_profiles)} 条用户画像示例数据")

if __name__ == "__main__":
    # 独立运行时初始化种子数据
    init_seed_data()